<template>
  <div class="page-container">
    <div class="content-wrapper">
      <!-- 顶部操作栏 -->
      <div class="top-actions">
        <div class="left-section">
          <h2 class="page-title">系统论文库</h2>
          <p class="page-description">浏览和下载系统提供的优质学术论文</p>
        </div>
        <el-input 
          v-model="searchText"
          placeholder="请输入论文名称或关键词"
          prefix-icon="el-icon-search"
          clearable
          class="search-input"
          @input="handleSearch"
        />
      </div>

      <!-- 文件列表标题 -->
      <div class="list-header">
        <div class="title">系统PDF论文列表</div>
        <div class="filter-section">
          <el-select 
            v-model="categoryFilter" 
            placeholder="选择分类" 
            clearable 
            size="small"
            class="category-filter"
            @change="handleCategoryChange"
          >
            <el-option label="全部" value=""></el-option>
            <el-option label="计算机科学" value="computer_science"></el-option>
            <el-option label="人工智能" value="artificial_intelligence"></el-option>
            <el-option label="机器学习" value="machine_learning"></el-option>
            <el-option label="深度学习" value="deep_learning"></el-option>
            <el-option label="数据科学" value="data_science"></el-option>
            <el-option label="网络安全" value="cybersecurity"></el-option>
          </el-select>
          <div class="filter-btn">
            <el-badge is-dot>
              <i class="el-icon-select"></i>
              <span>筛选</span>
            </el-badge>
          </div>
        </div>
      </div>

      <!-- 文件列表表格 -->
      <div class="table-container">
        <el-table 
          :data="filteredSystemPdfList" 
          stripe 
          class="file-table"
          highlight-current-row 
          show-overflow-tooltip
          header-row-class-name="custom-class"
          :header-cell-style="{
            background: '#f8f9fa',
            color: '#2c3e50',
            height: '40px',
          }"
          @row-click="handleRowClick"
          :row-class-name="getRowClassName"
        >
          <!-- 文件名称列 -->
          <el-table-column label="论文名称" min-width="200" max-width="300">
            <template v-slot="scope">
              <div class="file-name-cell">
                <img src="@/assets/icon/pdf-red.png" class="pdf-icon" alt="PDF"/>
                <div class="file-info">
                  <span class="file-name">{{ scope.row.name }}</span>
                  <span class="file-author" v-if="scope.row.author">作者: {{ scope.row.author }}</span>
                </div>
              </div>
            </template>
          </el-table-column>

          <!-- 分类列 -->
          <el-table-column label="分类" width="100">
            <template v-slot="scope">
              <el-tag
                :type="getCategoryType(scope.row.category)"
                size="small"
                style="display: flex; justify-content: center; align-items: center"
              >
                {{ getCategoryText(scope.row.category) }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 发布时间列 -->
          <el-table-column label="发布时间" width="100">
            <template v-slot="scope">
              <div class="time-cell">
                {{ formatTime(scope.row.publishTime) }}
              </div>
            </template>
          </el-table-column>

          <!-- 操作列 -->
          <el-table-column label="操作" width="300" fixed="right">
            <template v-slot="scope">
              <div class="action-buttons">
                <!-- 预览按钮 -->
                <el-button 
                  type="info" 
                  icon="el-icon-view" 
                  size="mini"
                  @click.stop="previewFile(scope.row)"
                  title="预览"
                >
                  预览
                </el-button>
                
                <!-- 下载按钮 -->
                <el-button 
                  type="success" 
                  icon="el-icon-download" 
                  size="mini"
                  @click.stop="downloadFile(scope.row)"
                  title="下载"
                >
                  下载
                </el-button>
                
                <!-- 收藏按钮 -->
                <el-button 
                  :type="scope.row.isFavorited ? 'warning' : 'default'"
                  :icon="scope.row.isFavorited ? 'el-icon-star-on' : 'el-icon-star-off'"
                  size="mini"
                  @click.stop="toggleFavorite(scope.row)"
                  :title="scope.row.isFavorited ? '取消收藏' : '收藏'"
                >
                  {{ scope.row.isFavorited ? '已收藏' : '收藏' }}
                </el-button>
              </div>
            </template>
          </el-table-column>

          <!-- 自定义空数据时展示的内容 -->
          <template #empty>
            <div class="empty-container">
              <el-empty :image="require('@/assets/svg/empty.svg')" description="暂无系统论文数据" :image-size="100"/>
            </div>
          </template>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handlePageSizeChange"
          @current-change="handlePageNumChange"
          :current-page="pageNum"
          :page-sizes="[4, 5]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
          small
          :pager-count="5"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs';
import { getCurrentUserId } from '@/utils/auth.js';

export default {
  name: 'SystemPdf',
  data() {
    return {
      systemPdfList: [],
      filteredSystemPdfList: [],
      searchText: '',
      categoryFilter: '',
      uid: getCurrentUserId() || 1,
      pageNum: 1,  // 当前页码
      pageSize: 5, // 每页显示的个数，默认6条
      total: 0,
      loading: false,
    };
  },
  methods: {
    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return '未知时间';
      return dayjs(timestamp).format('YYYY-MM-DD');
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (!bytes) return '未知大小';
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(1024));
      return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
    },

    // 获取分类文字
    getCategoryText(category) {
      const categoryMap = {
        'computer_science': '计算机科学',
        'artificial_intelligence': '人工智能',
        'machine_learning': '机器学习',
        'deep_learning': '深度学习',
        'data_science': '数据科学',
        'cybersecurity': '网络安全'
      };
      return categoryMap[category] || category;
    },

    // 获取分类类型
    getCategoryType(category) {
      const typeMap = {
        'computer_science': 'primary',
        'artificial_intelligence': 'success',
        'machine_learning': 'warning',
        'deep_learning': 'danger',
        'data_science': 'info',
        'cybersecurity': 'primary'
      };
      return typeMap[category] || '';
    },

    // 获取行样式类名
    getRowClassName({ row }) {
      if (row.isFavorited) {
        return 'favorited-row';
      }
      return '';
    },

    // 处理行点击
    handleRowClick(row) {
      // 点击行时预览文件
      this.previewFile(row);
    },

    // 预览文件
    previewFile(file) {
      try {
        // 在新窗口中打开预览
        window.open(file.previewUrl, '_blank');
        this.$message.success('正在打开预览...');
      } catch (error) {
        console.error('预览失败:', error);
        this.$message.error('预览失败，请重试');
      }
    },

    // 下载文件
    downloadFile(file) {
      try {
        // 创建下载链接
        const link = document.createElement('a');
        link.href = file.downloadUrl;
        link.download = file.name;
        link.target = '_blank';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        this.$message.success('开始下载文件');
      } catch (error) {
        console.error('下载失败:', error);
        this.$message.error('下载失败，请重试');
      }
    },

    // 切换收藏状态
    async toggleFavorite(file) {
      try {
        this.loading = true;
        const response = await this.$request.post('/system_pdf/toggle-favorite', {
          pdfId: file.id,
          userId: this.uid
        });
        
        if (response.code === '200') {
          file.isFavorited = !file.isFavorited;
          this.$message.success(file.isFavorited ? '收藏成功' : '取消收藏成功');
        } else {
          this.$message.error(response.msg || '操作失败');
        }
      } catch (error) {
        console.error('收藏操作失败:', error);
        this.$message.error('操作失败，请重试');
      } finally {
        this.loading = false;
      }
    },

    // 处理搜索
    handleSearch() {
      this.filterData();
    },

    // 处理分类筛选
    handleCategoryChange() {
      this.filterData();
    },

    // 过滤数据
    filterData() {
      let filtered = this.systemPdfList;

      // 按分类筛选
      if (this.categoryFilter) {
        filtered = filtered.filter(file => file.category === this.categoryFilter);
      }

      // 按搜索文本筛选
      if (this.searchText.trim()) {
        const searchLower = this.searchText.toLowerCase();
        filtered = filtered.filter(file => 
          file.name.toLowerCase().includes(searchLower) ||
          (file.author && file.author.toLowerCase().includes(searchLower))
        );
      }

      this.filteredSystemPdfList = filtered;
    },

    // 加载数据
    async load(pageNum) {
      if (pageNum) {
        this.pageNum = pageNum;
      }
      
      try {
        this.loading = true;
        const response = await this.$request.get('/system_pdf/page', {
          params: {
            PageNum: this.pageNum,
            PageSize: this.pageSize,
            name: this.searchText || undefined
          }
        });

        if (response.code === '200') {
          this.systemPdfList = response.data?.records || [];
          this.total = response.data?.total || 0;
          
          // 为每个文件添加默认字段
          this.systemPdfList.forEach(file => {
            // 添加默认字段以匹配前端期望的数据结构
            file.id = file.spid; // 使用spid作为id
            file.category = 'computer_science'; // 默认分类
            file.author = 'SDSE AIR'; // 默认作者
            file.publishTime = new Date().toISOString(); // 默认发布时间
            file.isFavorited = false; // 默认未收藏
          });
          
          // 获取用户收藏状态
          await this.loadFavoriteStatus();
          
          this.filterData(); // 应用搜索过滤
          console.log('加载的系统PDF列表:', this.systemPdfList);
        } else {
          this.$message.error('加载系统PDF列表失败：' + response.msg);
        }
      } catch (error) {
        console.error('加载系统PDF列表失败:', error);
        this.$message.error('加载系统PDF列表失败，请检查网络连接');
      } finally {
        this.loading = false;
      }
    },

    // 加载收藏状态
    async loadFavoriteStatus() {
      try {
        const response = await this.$request.get('/system_pdf/favorites', {
          params: { userId: this.uid }
        });
        
        if (response.code === '200') {
          const favoriteIds = response.data || [];
          this.systemPdfList.forEach(file => {
            file.isFavorited = favoriteIds.includes(file.id);
          });
        }
      } catch (error) {
        console.error('加载收藏状态失败:', error);
      }
    },

    // 处理页码变化
    handlePageNumChange(pageNum) {
      this.pageNum = pageNum;
      this.load(pageNum);
    },

    // 处理每页条数变化
    handlePageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.pageNum = 1; // 重置到第一页
      this.load(1);
    },
  },
  
  mounted() {
    this.load();
  }
};
</script>

<style scoped>
/* 页面容器 - 居中布局 */
.page-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding: 20px;
}

/* 内容包装器 - 居中显示 */
.content-wrapper {
  width: 100%;
  max-width: 1200px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 40px);
}

/* 顶部操作栏 */
.top-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 32px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-bottom: 1px solid #e9ecef;
}

.left-section {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0;
}

.page-description {
  font-size: 14px;
  color: #6c757d;
  margin: 0;
}

.search-input {
  width: 220px;
}

/* 文件列表标题 */
.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 32px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.filter-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.category-filter {
  width: 140px;
}

.filter-btn {
  background: #e9ecef;
  padding: 8px 16px;
  border-radius: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  min-width: 80px;
  justify-content: center;
}

.filter-btn:hover {
  background: #dee2e6;
  transform: translateY(-1px);
}

/* 表格容器 */
.table-container {
  flex: 1;
  padding: 0;
  overflow: hidden;
  min-width: 0;
}

.file-table {
  width: 100%;
  border-radius: 0;
  overflow: hidden;
  table-layout: fixed;
}

/* 文件名单元格 */
.file-name-cell {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  max-width: 100%;
  min-width: 0;
}

.pdf-icon {
  width: 24px;
  height: 24px;
  flex-shrink: 0;
  margin-top: 2px;
}

.file-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex: 1;
  min-width: 0;
}

.file-name {
  color: #2c3e50;
  font-size: 14px;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  min-width: 0;
}

.file-author {
  color: #6c757d;
  font-size: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  min-width: 0;
}

/* 时间单元格 */
.time-cell {
  color: #6c757d;
  font-size: 13px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

/* 文件大小单元格 */
.size-cell {
  color: #6c757d;
  font-size: 13px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 6px;
  align-items: center;
  flex-wrap: nowrap;
  justify-content: flex-start;
  width: 100%;
  padding: 0 8px;
}

/* 空状态容器 */
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
  background: #f8f9fa;
  border-radius: 12px;
  margin: 20px 0;
}

/* 分页容器 */
.pagination-container {
  padding: 10px 32px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 表格样式穿透 */
:deep(.custom-class) {
  font-size: 14px;
  font-weight: 600;
  height: 40px;
  background: #f8f9fa !important;
}

:deep(.el-table) {
  border: none;
  table-layout: fixed;
}

:deep(.el-table th) {
  background: #f8f9fa !important;
  color: #2c3e50 !important;
  font-weight: 600;
  border-bottom: 2px solid #dee2e6;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.el-table td) {
  padding: 16px 0;
  border-bottom: 1px solid #f1f3f4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.favorited-row) {
  background: #fff3cd;
}

:deep(.favorited-row:hover) {
  background: #ffeaa7 !important;
}

:deep(.el-table tbody tr:hover > td) {
  background: #f8f9fa !important;
}

/* 搜索框样式 */
:deep(.el-input__inner) {
  border: 2px solid #e9ecef;
  border-radius: 25px;
  padding: 12px 20px 12px 45px;
  background: white;
  transition: all 0.3s ease;
}

:deep(.el-input__inner:focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

:deep(.el-input__prefix) {
  left: 15px;
}

/* 按钮样式 */
:deep(.el-button--mini) {
  padding: 5px 10px;
  font-size: 12px;
  border-radius: 4px;
  transition: all 0.3s ease;
  min-width: auto;
  height: 30px;
  line-height: 1;
  white-space: nowrap;
}

:deep(.el-button--mini:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

:deep(.el-button--mini .el-icon) {
  margin-right: 3px;
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 12px;
  font-size: 12px;
  padding: 4px 10px;
  font-weight: 500;
}

/* 分页样式 */
:deep(.el-pagination) {
  text-align: center;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  flex-wrap: wrap;
  height: 40px;
}

:deep(.el-pagination .el-pager) {
  display: flex;
  align-items: center;
  gap: 4px;
  flex-wrap: nowrap;
  height: 32px;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 6px;
  margin: 0;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 32px;
  height: 32px;
  float: none;
}

:deep(.el-pagination .el-pager li.active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
}

:deep(.el-pagination .el-pager li:hover) {
  background: #e9ecef;
  transform: translateY(-1px);
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next) {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 32px;
  height: 32px;
  border-radius: 6px;
  float: none;
}

:deep(.el-pagination .el-pagination__sizes) {
  display: flex;
  align-items: center;
  margin: 0 8px;
  height: 32px;
}

:deep(.el-pagination .el-pagination__total) {
  display: flex;
  align-items: center;
  margin-right: 8px;
  height: 32px;
}

:deep(.el-pagination .el-pagination__jump) {
  display: flex;
  align-items: center;
  margin-left: 8px;
  white-space: nowrap;
  height: 32px;
}

:deep(.el-pagination .el-pagination__jump .el-input) {
  width: 50px;
  margin: 0 4px;
  display: flex;
  align-items: center;
}

:deep(.el-pagination .el-pagination__jump .el-input__inner) {
  text-align: center;
  padding: 0 4px;
  height: 32px;
  line-height: 32px;
  vertical-align: middle;
}

:deep(.el-pagination .el-pagination__jump .el-pagination__editor) {
  display: flex;
  align-items: center;
  height: 32px;
}

:deep(.el-pagination .el-pagination__jump .el-pagination__editor .el-input) {
  margin: 0 4px;
  display: flex;
  align-items: center;
}

:deep(.el-pagination .el-pagination__jump .el-pagination__editor .el-input__inner) {
  text-align: center;
  padding: 0 4px;
  height: 32px;
  line-height: 32px;
  vertical-align: middle;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: 10px;
  }
  
  .content-wrapper {
    border-radius: 12px;
  }
  
  .top-actions {
    padding: 16px 20px;
    flex-direction: column;
    gap: 16px;
  }
  
  .search-input {
    width: 100%;
  }
  
  .list-header {
    padding: 12px 20px;
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .filter-section {
    width: 100%;
    justify-content: space-between;
  }
  
  .table-container {
    padding: 0;
  }
  
  .pagination-container {
    padding: 12px 20px;
  }
  
  :deep(.el-table) {
    font-size: 12px;
  }
  
  :deep(.el-button--mini) {
    padding: 4px 8px;
    font-size: 11px;
  }
  
  .file-name-cell {
    gap: 8px;
  }
  
  .pdf-icon {
    width: 20px;
    height: 20px;
  }
}
</style> 